<?php
	require_once( 'core_DataBaseConnect.php' );
	require_once( '_configs.php' );
	
	class MemberDAO
	{
		// 중복되는 아이디의 유저가 있는가?
		public static function isSameID( DataBaseConnect $con, $id )
		{                
			$query = 'SELECT COUNT(*) FROM '.configs::TABLE_MEMBER." WHERE `ID`='$id';";
			$result = $con->query( $query );
			
			$row = DataBaseConnect::fetch_assoc($result);
			
			return ($row[ 'COUNT(*)' ] != '0');
		}
		// 중복되는 플랫폼의 유저가 있는가?
		public static function isSamePlatformMember( DataBaseConnect $con, $platform, $token )
		{                
			$query = 'SELECT COUNT(*) FROM '.configs::TABLE_MEMBER."
						WHERE 
							`PLATFORM_CODE`='$platform'
							AND
							`PLATFORM_TOKEN`='$token';";
			$result = $con->query( $query );
			
			$row = DataBaseConnect::fetch_assoc($result);
			
			return ($row[ 'COUNT(*)' ] != '0');
		}
		
		// 닉네임 중복
		public static function isSameNickname( DataBaseConnect $con, $nickname )
		{
			$query = 'SELECT COUNT(*) FROM '.configs::TABLE_MEMBER." WHERE `NICKNAME`='$nickname';";
			$result = $con->query( $query );
			
			$row = DataBaseConnect::fetch_assoc($result);
			
			return ($row[ 'COUNT(*)' ] != '0');
		}
		
		// 회원 가입
		public static function insertMember( DataBaseConnect $con,
												$id,
												$pass,
												$nickname,
												$sex,
												$birthYear,
												$region,
												$author,
												$activeKey )
		{
			// 유저의 고유키 생성
			$query = 'INSERT INTO '.configs::TABLE_MEMBER.' 
						(	`SEQ`,
							`ID`, 
							`PASS`, 
							`NICKNAME`, 
							`SEX`, 
							`BIRTH`,
							`REGION`, 
							`REGISTER`, 
							`AUTHOR`, 
							`STATUS`, 
							`ACTIVE_KEY`, 
							`LASTLOG`
						) 
						VALUES'.
						"(
							NULL,
							'$id', 
							'$pass', 
							'$nickname', 
							'$sex', 
							'$birthYear"."-01-01', 
							'$region',
							NOW(), 
							'$author', 
							'".configs::STATUS_DISACTIVE."', 
							'$activeKey', 
							NOW()	);";
			return $con->query( $query );
		}
		
		// 회원 가입
		public static function insertMemberForPlatform( DataBaseConnect $con,
												$platform,
												$token,
												$nickname,
												$sex,
												$birthYear,
												$region,
												$author )
		{
			// 유저의 고유키 생성
			$query = 'INSERT INTO '.configs::TABLE_MEMBER.' 
						(	`SEQ`,
							`PLATFORM_TOKEN`, 
							`PLATFORM_CODE`, 
							`NICKNAME`, 
							`SEX`, 
							`BIRTH`,
							`REGION`, 
							`REGISTER`, 
							`AUTHOR`, 
							`STATUS`,
							`LASTLOG`
						) 
						VALUES'.
						"(
							NULL,
							'$token', 
							'$platform', 
							'$nickname', 
							'$sex', 
							'$birthYear"."-01-01', 
							'$region',
							NOW(), 
							'$author', 
							'".configs::STATUS_ACTIVE."', 
							NOW()	);";
			return $con->query( $query );
		}
		// ID (=email) 로 검색
		public static function selectMemberByID( DataBaseConnect $con, $memberId )
		{
			$query 		= 'SELECT * FROM '.configs::TABLE_MEMBER." WHERE `ID`='$memberId' LIMIT 1;";
			return $con->query( $query );
		}
		// TOKEN 로 검색
		public static function selectMemberByPlatformToken( DataBaseConnect $con, $platform, $token )
		{
			$query 		= 'SELECT * FROM '.configs::TABLE_MEMBER." 
								WHERE 
									`PLATFORM_TOKEN`='$token' 
									AND
									`PLATFORM_CODE`='$platform' 
								LIMIT 1;";
			return $con->query( $query );
		}
		
		// 마지막 접속 로그
		public static function updateLastLog( DataBaseConnect $con, $memberSeq, $newSessionID )
		{
			$query = 'UPDATE '.configs::TABLE_MEMBER." 
						SET 
							`LASTLOG`=NOW(),
							`SESSION_ID` = '$newSessionID'
						WHERE 
							`SEQ`='$memberSeq';";
			return $con->query( $query );
		}
		// 전체 목록 수
		public static function countMembers( DataBaseConnect $con )
		{
			$query = 'SELECT COUNT(SEQ) FROM '.configs::TABLE_MEMBER.';';
			$fetch = DataBaseConnect::fetch_assoc( $con->query( $query ) );
			
			return $fetch[ 'COUNT(SEQ)' ];
		}
		// 모든 목록 가져오기
		public static function selectMembers( DataBaseConnect $con,
												$page,
												$numPerPage )
		{
			$startIndex = max( ($page-1)*$numPerPage, 0 );
			$query = 'SELECT * FROM '.configs::TABLE_MEMBER." LIMIT $startIndex,$numPerPage;";
			return $con->query( $query );
		}
		// SEQ 로 검색
		public static function selectMemberBySEQ( DataBaseConnect $con, $memberSeq )
		{
			$query 		= 'SELECT * FROM '.configs::TABLE_MEMBER." WHERE `SEQ`='$memberSeq' LIMIT 1;";
			return $con->query( $query );
		}
		// SESSION 유효성 검사
		public static function isCheckSessionID( DataBaseConnect $con, $memberSeq, $sessionID )
		{
			$query = 'SELECT COUNT(SEQ) FROM '.configs::TABLE_MEMBER." WHERE `SEQ`='$memberSeq' AND `SESSION_ID`='$sessionID' LIMIT 1;";
			$fetch = DataBaseConnect::fetch_assoc( $con->query( $query ) );
			return (int)$fetch[ 'COUNT(SEQ)' ] == 1;
		}
		public static function selectAuthor( DataBaseConnect $con, $seq )
		{
			$query		= 'SELECT AUTHOR FROM '.configs::TABLE_MEMBER." WHERE `SEQ`='$seq' LIMIT 1;";
			return $con->query( $query );
		}
		
		// 권한 유무 확인
		public static function isAccessable( DataBaseConnect $con, $memberSeq, array $accessTypes )
		{
			$result 	= self::selectAuthor( $con, $memberSeq );
			if( $fetch = DataBaseConnect::fetch_assoc( $result ) )
			{
				$index = array_search( $fetch[ 'AUTHOR' ], $accessTypes, false );
				return $index>-1;
			}
			return false;
		}
		
		// 유저 데이터 업데이트
		public static function updateMember( DataBaseConnect $con,
												$id,
												$nickname,
												$sex,
												$birthYear,
												$region,
												$author,
												$status )
		{
			$query = 'UPDATE '.configs::TABLE_MEMBER.
						" 	SET 
								`NICKNAME`='$nickname',
								`SEX`='$sex',
								`BIRTH`='$birthYear"."-01-01',
								`REGION`='$region',
								`AUTHOR`='$author',
								`STATUS`='$status'
							WHERE 
								`ID`='$id';";
			return $con->query( $query );
		}
		
		// 변경 가능한 닉네임인지 확인
		public static function isUpdatableNickname( DataBaseConnect $con, $id, $nickname )
		{
			$query = 'SELECT COUNT(*) FROM '.configs::TABLE_MEMBER." WHERE `NICKNAME`='$nickname' AND `ID`!='$id';";
			$result = $con->query( $query );
			
			$row = DataBaseConnect::fetch_assoc($result);
			
			return ($row[ 'COUNT(*)' ] == '0');
		}
		
		
		// 클라이언트 전용 ------------------------------------------------------------
		// 유저 데이터 업데이트
		public static function updateMember_client( DataBaseConnect $con,
												$id,
												$nickname,
												$sex,
												$birthYear,
												$region )
		{
			$query = 'UPDATE '.configs::TABLE_MEMBER.
						" 	SET 
								`NICKNAME`='$nickname',
								`SEX`='$sex',
								`BIRTH`='$birthYear"."-01-01',
								`REGION`='$region'
							WHERE 
								`ID`='$id';";
			return $con->query( $query );
		}
		
		
		//-------------------------------- 이하 보류 -----
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		// 멤버가 선택한 카테고리 정보를 가져옴
		public static function selectMemberCategory( DataBaseConnect $con,
														$member_seq )
		{
			$query = 'SELECT * FROM '.configs::TABLE_MEMBERCATEGORY." WHERE M_SEQ='$member_seq';";
			return $con->query( $query );
		}
		
		// 유저의 멤버 카테고리를 갱신
		public static function updateMemberCategory( DataBaseConnect $con,
														$member_seq,
														array $categoryIds,
														array $categoryPoints )
		{
			while( count( $categoryIds ) > 0 )
			{
				$cId = array_shift( $categoryIds );
				$cPoint = array_shift( $categoryPoints );
				
				$query = 'SELECT COUNT(*) FROM '.configs::TABLE_MEMBERCATEGORY." WHERE `M_SEQ`='$member_seq' AND `C_ID`='$cId';";
				$fetch = DataBaseConnect::fetch_assoc( $con->query( $query ) );
				
				if( $fetch[ 'COUNT(*)' ] != '0' )
				{
					// 업데이트
					$query = 'UPDATE '.configs::TABLE_MEMBERCATEGORY." SET `POINT`='$cPoint' WHERE `M_SEQ`='$member_seq' AND `C_ID`='$cId';";
				}else{
					// 추가
					$query = 'INSERT INTO '.configs::TABLE_MEMBERCATEGORY.'
						 (`SEQ`, `M_SEQ`, `C_ID`, `POINT`) 
						 VALUES'. 
						 "(NULL, '$member_seq', '$cId', '$cPoint');";
				}
				$con->query( $query );
			}
		}
		
		
		
		
		
		
		
		
		// 유저의 즐겨찾기 모델 정보를 갱신( 상세 값을 입력하지 않으므로, 삭제후 다시 기록한다.
		public static function insertMemberModel( DataBaseConnect $con,
														$member_seq,
														$model_seq )
		{
			// 기존값 확인
			$query = 'SELECT COUNT(*) FROM '.configs::TABLE_MEMBERMODEL." WHERE `MEM_SEQ`='$member_seq' AND `MO_SEQ`='$model_seq' LIMIT 1;";
			$result = $con->query( $query );
			$fetch = DataBaseConnect::fetch_assoc( $result );
			if( $fetch[ 'COUNT(*)' ] == 0 )
			{
				// 업다면, 입력
				$query = 'INSERT INTO '.configs::TABLE_MEMBERMODEL.'
				(`SEQ`, `MEM_SEQ`, `MO_SEQ` )
				VALUES'.
				"(NULL, '$member_seq', '$model_seq' );";
				$con->query( $query );
			}
		}
		// 유저가 즐겨찾기한 모델인가
		public static function isFavoriteModel( DataBaseConnect $con,
														$member_seq,
														$model_seq )
													
		{
			$query = 'SELECT COUNT(*) FROM '.configs::TABLE_MEMBERMODEL."
						WHERE
							`MEM_SEQ`='$member_seq' AND
							`MO_SEQ`='$model_seq';";
			$result = $con->query( $query );
			$fetch = DataBaseConnect::fetch_assoc( $result );
			return ( $fetch[ 'COUNT(*)' ] > 0 );
		}
		// 즐겨찾기 모델 삭제
		public static function deleteMemberModel( DataBaseConnect $con,
														$member_seq,
														$model_seq )
		{
			$query = 'DELETE FROM '.configs::TABLE_MEMBERMODEL."
						WHERE
							`MEM_SEQ`='$member_seq' AND
							`MO_SEQ`='$model_seq' 
						LIMIT 1;";
			return $con->query( $query );
		}
		// 유저가 등록한 즐겨찾기 항목 수
		public static function countMemberModels( DataBaseConnect $con
													, $member_seq )
		{
			$query = 'SELECT COUNT(*) FROM '.configs::TABLE_MEMBERMODEL." 
						WHERE
							`MEM_SEQ`='$member_seq';";
			$result = $con->query( $query );
			$fetch = DataBaseConnect::fetch_assoc( $result );
			return $fetch[ 'COUNT(*)' ];
		}
		// 유저가 등록한 즐겨찾기 목록
		public static function selectMemberModels( DataBaseConnect $con
													, $member_seq
													, $page
													, $numPerPage )
		{
			$startIndex = max( ($page-1)*$numPerPage, 0 );
			$query = 'SELECT * FROM '.configs::TABLE_MEMBERMODEL." 
						WHERE
							`MEM_SEQ`='$member_seq'
						LIMIT 
							$startIndex,$numPerPage;";
			return $con->query( $query );
		}
		// 유저가 등록한 모든 코멘트 수
		public static function countMemberModelComments( DataBaseConnect $con
													, $member_seq )
		{
			$query = 'SELECT COUNT(*) FROM '.configs::TABLE_MODELCOMMENTS." 
						WHERE
							`MEM_SEQ`='$member_seq';";
			$result = $con->query( $query );
			$fetch = DataBaseConnect::fetch_assoc( $result );
			return $fetch[ 'COUNT(*)' ];
		}
		// 유저가 등록한 모든 코멘트 목록
		public static function selectMemberModelComments( DataBaseConnect $con
														, $member_seq
													, $page
													, $numPerPage )
		{
			$startIndex = max( ($page-1)*$numPerPage, 0 );
			$query = 'SELECT * FROM '.configs::TABLE_MODELCOMMENTS."
						WHERE 
							`MEM_SEQ`='$member_seq'
						LIMIT
							$startIndex,$numPerPage";
			return $con->query( $query );
		}
	}
?>